package org.bangumibuddy.security.service;

import org.bangumibuddy.dto.UserDto;
import org.bangumibuddy.pojo.token.TokenData;
import org.bangumibuddy.entity.UserEntity;
import org.bangumibuddy.exception.PasswordErrorException;
import org.bangumibuddy.mapper.UserMapper;
import org.bangumibuddy.security.entity.BangumiAuthenticationToken;
import org.bangumibuddy.security.entity.BangumiUserDetail;
import org.bangumibuddy.utils.JwtManager;
import org.bangumibuddy.utils.Role2StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class BangumiUserDetailService implements UserDetailsService {

    @Autowired
    JwtManager jwtManager;

    @Autowired
    AuthenticationConfiguration authenticationConfiguration;

    @Autowired
    private UserMapper userMapper;

    public TokenData ValidateUser(UserDto userDto) throws Exception {
        UsernamePasswordAuthenticationToken unauthenticated = UsernamePasswordAuthenticationToken.unauthenticated(userDto.getUsername(), userDto.getPassword());
        AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
        Authentication authenticated = authenticationManager.authenticate(unauthenticated);

        //验证失败
        if(authenticated == null || !authenticated.isAuthenticated())
            throw new PasswordErrorException();

        //获取的token不是BangumiAuthenticationToken
        if(!(authenticated instanceof BangumiAuthenticationToken userToken))
            throw new RuntimeException("服务器错误！");

        //验证成功
        return jwtManager.creteTokens(userToken.getUserName(),userToken.getEmail(), userToken.getRole());
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserEntity user = userMapper.getByUsernameOrEmail(username);

        if(user == null)
            throw new UsernameNotFoundException("用户不存在");

        return BangumiUserDetail.builder()
                .userName(user.getUserName())
                .email(user.getEmail())
                .role(Role2StringUtil.role2String(user.getRole()))
                .password(user.getPassword())
                .build();
    }
}
